package TwoAgain;

import com.lovo.netCRM.component.LovoButton;
import com.lovo.netCRM.component.LovoLabel;
import com.lovo.netCRM.component.LovoTable;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ShopFrame extends JFrame {
    private LovoTable table = new LovoTable(this,new String[]{"编号","名字","单价","数量"},new String[]{"Commodity.code",
            "Commodity.name","Commodity.price","num"}, "Commodity.code");
    private Commodity commodity;

    private IShopService shopService = new ShopServiceImpl();
    private LovoLabel totalPriceLabel = new LovoLabel("总价",200,420,this);

    public ShopFrame(Commodity c){
        this.commodity = c;

        this.setLayout(null);
        this.init();

        this.setSize(400,500);
        this.setVisible(true);
        this.setDefaultCloseOperation(3);
        this.setLocationRelativeTo(null);
    }

    private void init(){
        shopService.buyCommodity(commodity);
        showTable();


        table.setSizeAndLocation(50,60,300,300);
        LovoLabel label = new LovoLabel("购物车商品如下",20,20,this);
        LovoButton backButton = new LovoButton("返回",250,390,this);
        LovoButton delButton = new LovoButton("删除",50,390,this);
        LovoButton upDataNumButton = new LovoButton("修改数量",50,420,this);

        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                new MainFrame();
            }
        });

        delButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                delete();
            }
        });

        upDataNumButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateNum();
            }
        });
    }


    private void updateNum(){
        int x = table.getKeyByInt();
        if (x==-1){
            JOptionPane.showMessageDialog(null,"请选中商品");
            return;
        }else {
            String s = JOptionPane.showInputDialog(null,"输入修改的数量");
            shopService.updateNum(x,Integer.parseInt(s));
            this.showTable();
        }
    }

    private void delete(){
        int x = table.getKeyByInt();
        if (x==-1){
            JOptionPane.showMessageDialog(null,"请选中商品");
            return;
        }else {
            shopService.delCommodity(x);
            this.showTable();
        }
    }

    private void showTable(){
        table.updateLovoTable(shopService.findAll());
        this.totalPriceLabel.setText(shopService.totalPrice()+"");
    }



}
